<template>
  <div class="data-import">
    <el-alert
      title="数据导入功能"
      type="info"
      description="从JSON或Excel文件导入数据到系统，支持增量更新或完全替换。"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    />
    
    <el-form :model="importForm" label-width="120px">
      <el-form-item label="导入方式">
        <el-radio-group v-model="importForm.mode">
          <el-radio label="merge">合并数据（增量更新）</el-radio>
          <el-radio label="replace">替换数据（完全覆盖）</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="选择文件">
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          :file-list="fileList"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">
              支持 .json 或 .xlsx 文件，文件大小不超过 10MB
            </div>
          </template>
        </el-upload>
      </el-form-item>
      
      <el-form-item>
        <el-button 
          type="primary" 
          @click="handleImport" 
          :loading="importing"
          :disabled="!selectedFile"
        >
          开始导入
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    
    <div v-if="importProgress.show" class="import-progress">
      <h3>导入进度</h3>
      <el-progress 
        :percentage="importProgress.percentage" 
        :status="importProgress.status"
      />
      <p>{{ importProgress.message }}</p>
    </div>
    
    <div v-if="importHistory.length > 0" class="import-history">
      <h3>导入历史</h3>
      <el-table :data="importHistory" style="width: 100%">
        <el-table-column prop="date" label="导入时间" width="180" />
        <el-table-column prop="filename" label="文件名称" />
        <el-table-column prop="mode" label="导入方式" width="120">
          <template #default="scope">
            {{ scope.row.mode === 'merge' ? '增量更新' : '完全替换' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
              {{ scope.row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { importData, getImportHistory } from '@/api/migration'

export default {
  name: 'DataImport',
  data() {
    return {
      importForm: {
        mode: 'merge'
      },
      fileList: [],
      selectedFile: null,
      importing: false,
      importProgress: {
        show: false,
        percentage: 0,
        status: '',
        message: ''
      },
      importHistory: []
    }
  },
  created() {
    this.fetchImportHistory()
  },
  methods: {
    async fetchImportHistory() {
      try {
        // 实际项目中应该调用API获取历史记录
        // const { data } = await getImportHistory()
        // this.importHistory = data
        
        // 使用模拟数据
        this.importHistory = [
          {
            id: 1,
            date: '2023-05-31 11:45:20',
            filename: 'products_export_20230531.json',
            mode: 'merge',
            status: 'success'
          },
          {
            id: 2,
            date: '2023-05-29 09:15:33',
            filename: 'full_backup_20230529.xlsx',
            mode: 'replace',
            status: 'success'
          }
        ]
      } catch (error) {
        console.error('获取导入历史失败:', error)
        this.$message.error('获取导入历史失败')
      }
    },
    
    handleFileChange(file) {
      this.selectedFile = file.raw || file
      console.log('文件已选择:', this.selectedFile)
      
      // 确保fileList数组被更新
      if (file) {
        this.fileList = [file]
      }
    },
    
    async handleImport() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择要导入的文件')
        return
      }
      
      const fileExt = this.selectedFile.name.split('.').pop().toLowerCase()
      if (!['json', 'xlsx', 'xls'].includes(fileExt)) {
        this.$message.error('只支持 JSON 或 Excel 格式的文件')
        return
      }
      
      this.importing = true
      this.importProgress = {
        show: true,
        percentage: 0,
        status: '',
        message: '正在准备导入...'
      }
      
      try {
        // 模拟导入过程
        await this.simulateImport()
        
        // 实际项目中应该调用后端API进行导入
        // const formData = new FormData()
        // formData.append('file', this.selectedFile.raw)
        // formData.append('mode', this.importForm.mode)
        // const response = await importData(formData)
        
        this.$message.success('数据导入成功')
        
        // 添加到导入历史
        this.importHistory.unshift({
          id: Date.now(),
          date: new Date().toLocaleString(),
          filename: this.selectedFile.name,
          mode: this.importForm.mode,
          status: 'success'
        })
        
        this.resetForm()
      } catch (error) {
        console.error('导入失败:', error)
        this.$message.error('导入失败，请重试')
        this.importProgress.status = 'exception'
        this.importProgress.message = '导入失败: ' + error.message
      } finally {
        this.importing = false
      }
    },
    
    resetForm() {
      this.importForm = {
        mode: 'merge'
      }
      this.fileList = []
      this.selectedFile = null
    },
    
    async simulateImport() {
      // 模拟导入进度
      for (let i = 0; i <= 100; i += 10) {
        this.importProgress.percentage = i
        
        if (i === 0) {
          this.importProgress.message = '正在验证文件...'
        } else if (i === 30) {
          this.importProgress.message = '正在解析数据...'
        } else if (i === 60) {
          this.importProgress.message = '正在导入数据...'
        } else if (i === 90) {
          this.importProgress.message = '正在完成导入...'
        } else if (i === 100) {
          this.importProgress.status = 'success'
          this.importProgress.message = '导入完成！'
        }
        
        await new Promise(resolve => setTimeout(resolve, 300))
      }
    }
  }
}
</script>

<style scoped>
.data-import {
  padding: 10px 0;
}

.import-progress {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.import-progress h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
}

.import-history {
  margin-top: 30px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.import-history h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
}
</style> 